<?php

namespace Beerus\Modules\Wiki\Controllers;

use App\Admin\Extensions\Tools\GridView;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\wiki\TbkGoods;
use Biz\model\brand\Brand as mBrand;
use Biz\model\store\StoreBasic as mStoreBasic;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\pockets\export\ExportData;
use Biz\service\wiki\AdmWiki;
use Biz\service\wiki\AdmWikiTag;
use Biz\service\wiki\SelectionLib;
use Biz\service\wiki\Wiki;
use Biz\tools\RealUrl;
use Doraemon\model\AdmComplian as mAdmComplian;
use Doraemon\model\DevidePackage\PackageRelatedInfo;
use Doraemon\model\Elasticsearch\EsWikiListModel;
use Doraemon\service\Category;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;

class AdmController extends Controller
{

    const PAGE_SIZE = 50;
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';
    const PACKAGE_RELATED_CHECKD = 1;
    const PACKAGE_EDIT_TYPE = 1;
    const UP_SCENE_IMG_YES = 1; //把主图设置为场景图-yes
    const UP_SCENE_IMG_NO = 2; //把主图设置为场景图-no
    const UP_SCENE_IMG_DEL = 3; //清空场景图

    public function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request, Content $content)
    {
        Admin::script($this->offlineScript());
        $requestParams = $request->all();
        $tabType = $request->input('tab_type', 1);
        $condition = $this->_index_condition($requestParams);
        if ($tabType == 1) {
            $condition['brand_id'] = 0;
            $condition['store_id'] = 0;
        } elseif ($tabType == 2) {
            $condition['brand_id[>]'] = 0;
        } else {
            $condition['store_id[>]'] = 0;
        }
        $category_id = $requestParams['category_id'] ?? 0;
        $second_category_id = $requestParams['second_category_id'] ?? 0;
        $third_category_id = $requestParams['third_category_id'] ?? 0;
//        $four_category_id = $requestParams['four_category_id'] ?? 0;
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
//
//        $sort = [];
//        if (isset($requestParams["_sort"]['column']) && $requestParams["_sort"]['column'] == "hot") {
//            $sort['type'] = $requestParams["_sort"]['type'];
//            $sort['column'] = $requestParams["_sort"]['column'];
//        }
        $styleList = AdmWikiTag::getStyleList();
        $styleList = array_combine($styleList, $styleList);
        $wikiList = AdmWiki::admWikiList($condition);
        $gridModel = new pGridDataModel($wikiList['list'], $wikiList['total'], [
            'perPage' => $pageSize
        ]);

        $query = $this->_filter_request($request);
        Admin::script($this->reloadScript($query));
        Admin::script($this->editLikeScript());
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $category_id, $query, $condition, $request, $tabType, $second_category_id, $third_category_id, $styleList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) use ($category_id, $query, $condition, $request, $tabType, $second_category_id, $third_category_id, $styleList) {

                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) use ($tabType) {
                        // 在这里添加字段过滤器
                        $filter->dropDown('wiki_value', [
                            'wiki_type' => '商品名称',
                            'wiki_id' => '商品ID',
                            'basic_id' => 'wikiID',
                            'channel_spu_id' => '第三方商品id'
                        ]);
                        if ($tabType == 2) {
                            $filter->dropDown('brand_value', [
                                'brand_id' => '品牌ID',
                                'brand_name' => '品牌名称',
                                'brand_type' => '品牌/店铺账号昵称',
                                'brand_value' => '品牌/店铺账号ID',
                            ]);
                        } elseif ($tabType == 3) {
                            $filter->dropDown('brand_value', [
                                'store_id' => '门店ID',
                                'store_name' => '门店名称',
                            ]);
                        }

                        //时间筛选
                        $filter->between('date_time', '创建时间')->datetime()->condition($_GET);

                        $filter->equal('shop_name', '店铺名称')->placeholder('店铺名称');
                    });
                    $filter->column(1 / 3,
                        function ($filter) use ($category_id, $second_category_id, $third_category_id) {
                            $topCategory = AdmWiki::admGetChildCategoryMap(0);
                            ksort($topCategory);
                            $filter->equal('category_id', '商城类目(一级)')->select($topCategory)->load('second_category_id',
                                self::SOURCE_CATEGORY_LIST);

                            $secondCategory = $category_id > 0 ? AdmWiki::admGetChildCategoryMap($category_id) : [];
                            $filter->equal('second_category_id',
                                '商城类目(二级)')->select($secondCategory)->load('third_category_id',
                                self::SOURCE_CATEGORY_LIST);

                            $thirdCategory = $second_category_id > 0 ? AdmWiki::admGetChildCategoryMap($second_category_id) : [];
                            $filter->equal('third_category_id',
                                '商城类目(三级)')->select($thirdCategory)->load('four_category_id',
                                self::SOURCE_CATEGORY_LIST);
                            $fourCategory = $third_category_id > 0 ? AdmWiki::admGetChildCategoryMap($third_category_id) : [];
                            $filter->equal('four_category_id', '商城类目(四级)')->select($fourCategory);

                        });
                    $filter->column(1 / 3, function ($filter) use ($styleList) {
                        $filter->equal('channel_type', '商品来源')->multipleSelect(mWiki::CHANNEL_TYPE_MAP);
                        $filter->equal('channel_spu_status', '商品第三方状态')->select(mWiki::CHANNEL_STATUS_ARR);
                        $filter->equal('status', '审核状态')->select(mWiki::ADM_STATUS_MAP);
                        $filter->equal('reason', '未审核原因')->select(AdmWiki::REJECT_MSG_MAP);
                        $filter->equal('wiki_basic_style', '风格标签')->select($styleList);
                    });
                    if (!empty($condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->column('id', '商品ID')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->id . '</li>';
                    $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $this->url . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                    $html .= '<a target="_blank" href="' . $this->url . '">链接</a></li>';
                    $html .= '<li><a target="_blank" href="' . admin_url('/wiki/shareWiki?wiki_id=' . $this->id) . '">关联数:' . $this->relate_num . '</a></li>';
                    $html .= '<li><a target="_blank" href="' . admin_url('/album/albumcheck?wiki_id=' . $this->id) . '">关联清单数:' . $this->album_count . '</a></li>';
                    $html .= '</ul>';
                    return $html;
                })->width(100);
                $grid->column('basic_id', 'WIKI ID')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->basic_id . '</li>';
                    if ($this->is_official) {
                        $html .= '<li><span class="label label-success">官方</span></li>';
                        if ($this->is_default) {
                            $html .= '<li><span class="label label-info">默认</span></li>';
                        }
                    } else if ($this->brand_id && $this->brand_info['brand_type']) {
                        $html .= '<li><a class="label label-default set-official" data-id="' . $this->id . '">设置官方</a></li>';
                    }
                    $html .= '</ul>';
                    return $html;
                })->width(70);
                $grid->column('title', '商品名称')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>' . $this->title . '</li>';
                    $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $this->channel_spu_id . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                    $html .= $this->channel_spu_id . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('hot', '热度/价格')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>热度：' . $this->hot . '</li>';
                    $html .= '<li>最低价：' . $this->min_price . '</li>';
                    $html .= '<li>最高价：' . $this->max_price . '</li>';
                    $html .= '<li>收藏数：' . $this->fav_count . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->width(120);
                $grid->column('card_img', '首图')->width(200)->display(function () {
                    $imgPath = $this->cover_img;
                    $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:150px;height:150px;' class='img img-thumbnail' />" : "";
                    $html = '';
                    if ($image) {
                        $html .= '<a href="javascript:layer.open({type: 2,shadeClose: true,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $imgPath . '\'});">';
                        $html .= $image;
                        $html .= '</a>';
                    }
                    return $html;
                })->width(150);
                if ($tabType != 3) {
                    $grid->column('channel_brand', '品牌')->width(150);
                    $grid->column('channel_shop_name', '店铺名称')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= '<li>' . $this->channel_shop_name . '</li>';
                        $channelShopUrl = RealUrl::getShopUrl($this->channel_type, $this->channel_shop_id, $this->channel_seller_id);
                        if ($channelShopUrl) {
                            $html .= '<li><a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $channelShopUrl . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                            $html .= '<a target="_blank" href="' . $channelShopUrl . '">店铺链接</a></li>';
                        }

                        $html .= '</ul>';
                        return $html;
                    })->width(150);
                }
                if ($tabType == 2) {
                    $grid->column('brand_info', '品牌/店铺账号')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        if ($this->brand_uid) {
                            $html .= '<li>UID:' . $this->brand_uid . '</li>';
                        }
                        if ($this->brand_nick) {
                            $html .= '<li>昵称:' . $this->brand_nick . '</li>';
                        }
                        if ($this->brand_info) {
                            $html .= '<li>类型:<span class="label label-success">' . (mBrand::BRAND_TYPE[$this->brand_info['brand_type']] ?: '默认') . '</span></li>';
                            $html .= '<li>品牌ID:' . $this->brand_info['id'] . '</li>';
                            $html .= '<li>品牌名:' . $this->brand_info['name'] . '</li>';
                        }
                        $html .= '</ul>';
                        return $html;
                    })->width(180);
                } elseif ($tabType == 3) {
                    $grid->column('store_info', '门店账号')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= '<li>ID:' . $this->store_info['id'] . '</li>';
                        $html .= '<li>UID:' . $this->store_info['uid'] . '</li>';
                        $html .= '<li>名称:' . $this->store_info['name'] . '</li>';
                        $html .= '</ul>';
                        return $html;
                    })->width(200);
                }
                $grid->column('channel_spu_status', '渠道/状态')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    if ($this->channel_type) {
                        $html .= '<li><span>' . mWiki::CHANNEL_TYPE_MAP[$this->channel_type] . '</span></li>';
                    }
                    $labelStyle = ($this->channel_spu_status == mWiki::CHANNEL_SPU_STATUS_OFF) ? 'danger' : 'success';
                    $labelSapn = ($this->channel_spu_status == mWiki::CHANNEL_SPU_STATUS_OFF) ? '失效' : '有效';
                    $html .= '<li><span class="label label-' . $labelStyle . '">' . $labelSapn . '</span></li>';
                    if ($this->channel == mWiki::CHANNEL_TAOBAO) {
                        $isTbkArr = TbkGoods::isTbkGoods([$this->channel_spu_id]);
                        if ($isTbkArr[$this->channel_spu_id]) {
                            $html .= '<li><span class="label label-info">淘宝客</span></li>';
                        }
                    }
                    $html .= '</ul>';
                    return $html;
                })->width(90);
                $grid->column('addtime', '创建时间')->width(100);
                $grid->column('status_desc', '状态')->width(70);
                $grid->column('category_desc', '类目')->width(100);
                $grid->column('wiki_basic_style', '风格标签')->width(100);
                $grid->tools(function ($tools) {
                    $tools->append(new GridView());
                    $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>');
                });

                //@param card_img card_extend
                if ($request->get('view') === 'card') {
                    $grid->column('card_img', '首图')->width(200)->display(function () {
                        $imgPath = $this->cover_img;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='height:200px' class='img img-thumbnail' />" : "";
                        return $image;
                    });
                    //card_title
                    $grid->column('card_extend', '更多信息')->display(function () {
                        $title = mb_strlen($this->title) > 15 ? mb_substr($this->title, 0, 15) . '...' : $this->title;
                        return $this->id . ' ' . $title;
                    })->modal('更多信息', function () use ($grid) {
                        $rows = [];
                        foreach ($grid->visibleColumns() as $column) {
                            if (!in_array($column->getName(), ['card_img', '__actions__'])) {
                                $rows[] = [$column->getLabel(), $this->{$column->getName()}];
                            }
                        }
                        $table = new Table([], $rows);
                        return $table->render();
                    });
                    $grid->setView('wiki::index.card');
                }

                $grid->actions(function (Grid\Displayers\Actions $actions) use ($query) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if (!Admin::user()->isRole('parttime.user')) {
                        $actions->prepend('<a class="fa fa-edit like-data" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>调整喜爱数</a>');
                        if ($actions->row->channel != mWiki::CHANNEL_NOTHING) {
                            $actions->prepend('<a class="fa fa-refresh reload-data" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>重新抓取</a>');
                        }
                    }
                    if ($actions->row->status != mWiki::STATUS_DEL) {
                        if (!Admin::user()->isRole('parttime.user')) {
                            $actions->prepend('<a class="fa fa-trash offline-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">下架</a>');
                        }
                        $actions->prepend('<a class="fa fa-edit" href="admList/' . $actions->row->id . '/edit?' . $query . '">编辑</a>');
                    }
                    if (!Admin::user()->isRole('parttime.user')) {
                        if ($actions->row->channel != mWiki::CHANNEL_NOTHING) {
                            $actions->prepend('<a class="fa fa-chain" href="javascript:layer.open({
                                type: 2,
                                title: \'第三方链接\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $actions->row->url . '\'
                            });">链接</a>');
                        }

                        $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $actions->row->h5_url . '\'
                            });">预览</a>');
                    }
                });
            }
        );
        $tab = new Tab();
        if ($tabType == 1) {
            $tab->add('住友wiki', $gridList->render(), true);
            if (!Admin::user()->isRole('parttime.user')) {
                $tab->addLink('品牌wiki', url('/admin/wiki/admList?tab_type=2'));
                $tab->addLink('门店wiki', url('/admin/wiki/admList?tab_type=3'));
            }
        } elseif ($tabType == 2) {
            $tab->addLink('住友wiki', url('/admin/wiki/admList?tab_type=1'));
            if (!Admin::user()->isRole('parttime.user')) {
                $tab->add('品牌wiki', $gridList->render(), true);
                $tab->addLink('门店wiki', url('/admin/wiki/admList?tab_type=3'));
            }
        } else {
            $tab->addLink('住友wiki', url('/admin/wiki/admList?tab_type=1'));
            if (!Admin::user()->isRole('parttime.user')) {
                $tab->addLink('品牌wiki', url('/admin/wiki/admList?tab_type=2'));
                $tab->add('门店wiki', $gridList->render(), true);
            }
        }
        return $content
            ->header('wiki商品')
            ->description(' ')
            ->row($tab);
    }

    public function abnormal(Request $request, Content $content)
    {
        $query = $this->_filter_request($request);
        Admin::script($this->reloadScript($query));
        Admin::script($this->offlineScript());
        $requestParam = $request->all();
        $condition = [];
        if (isset($requestParam['wiki_id']) && ($requestParam['wiki_id'] > 0)) {
            $condition['from'] = 'wiki_id:' . $requestParam['wiki_id'];
        }
        if (isset($requestParam['addtime']['start']) && strlen($requestParam['addtime']['start'])) {
            $condition['addtime[>=]'] = strtotime($requestParam['addtime']['start']);
        }
        if (isset($requestParam['addtime']['end']) && strlen($requestParam['addtime']['end'])) {
            $condition['addtime[<=]'] = strtotime($requestParam['addtime']['end']);
        }
        if (isset($requestParam['reason']) && $requestParam['reason']) {
            $condition['type'] = $requestParam['reason'];
        }
        if (isset($requestParam['keyword']) && strlen($requestParam['keyword'])) {
            $condition['message[~]'] = $requestParam['keyword'];
        }

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $wikiList = AdmWiki::abnormalWikiList($condition);
        $gridModel = new pGridDataModel($wikiList['list'], $wikiList['total']);

        return $content
            ->header('异常商品列表')
            ->description(' ')
            ->row(
                Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $condition) {
                        $grid->paginate($gridModel->getPerPage());
                        $grid->filter(function ($filter) use ($condition) {
                            $filter->disableIdFilter();
                            $filter->column(1 / 2, function ($filter) {
                                $filter->equal('wiki_id', '商品ID')->placeholder('商品id');
                                $filter->equal('reason', '原因')->select(mAdmComplian::WIKI_MSG_MAP);
                            });
                            $filter->column(1 / 2, function ($filter) {
                                $filter->dropDown('time', [
                                    'addtime' => '提报时间',
                                ])->betweenDatetime();
                                $filter->equal('keyword', '关键词')->placeholder('报错关键词查询');
                            });
                            if (!empty($condition)) {
                                $filter->expand();//默认展开
                            }
                        });
                        $grid->disableCreateButton();
                        $grid->disableExport();
                        $grid->disableRowSelector();
                        $grid->disableActions();

                        $grid->column('wiki_id', '商品ID')->width(50);
                        $grid->column('uid', '用户ID')->width(50);
                        $grid->column('nick', '用户昵称')->width(100);
                        $grid->column('addtime', '提报时间')->width(150);
                        $grid->column('reason', '原因')->width(150);
                        $grid->column('desc',
                            '描述')->width(200)->style('word-break:break-all; word-wrap:break-word; white-space:inherit');
                    }
                )
            );
    }


    /**
     * 请求表单验证
     *
     * @param array $checkRule 验证规则
     * @param array $data 要验证的数据
     * @return int
     */
    public static function validatorRule(array $checkRule, array $data)
    {
        $messages = [
            'required' => '参数 :attribute是必须传递参数.',
            'max' => '参数 :attribute 不能大于 :max.',
            'integer' => '参数 :attribute是必须是整型',
            'numeric' => '参数 :attribute是必须是数字',
            'url' => '参数 :attribute是必须是连接',
            'json' => '参数 :attribute是必须是json',
            'date' => '参数 :attribute是必须是日期类型的',
            'in' => '参数 :attribute不是指定的类型',
        ];
        $validator = Validator::make($data, $checkRule, $messages);

        if ($validator->fails()) {
            //获取错误的方法是 errors
            return $msg = $validator->errors()->first();//返回第一个
        }
        return true;
    }

    /**
     * 通过package_id获取wiki列表
     * @param Request $request
     * @param Content $content
     * @return Content|\Illuminate\Http\JsonResponse
     */
    public function wikiListByPackageId(Request $request, Content $content)
    {
        $params = $request->all();
        $rules = [
            'package_id' => "required|integer",
            'wiki_id' => "integer",
            'page' => "integer",
        ];
        //验证参数
        $returnMsg = self::validatorRule($rules, $params);
        if ($returnMsg !== true) {
            $msg = [
                'message' => $returnMsg,
                'code' => 0,
            ];
//            return redirect('/'.$request->getQueryString())->with(compact('msg'));
            return response()->json($msg);

        }

        $id = isset($params['id']) ? $params['id'] : '';

        $page = isset($params['page']) ? $params['page'] : 1;

        $pageSize = 20;

        $packageId = $params['package_id'];
        $where['package_id'] = $packageId;
        $where['wiki_id[>]'] = 0;
        $info = PackageRelatedInfo::select(['wiki_id', 'id'], $where);

        $ids = array_column($info, 'wiki_id');
        if (!empty($id)) {
            if (in_array($id, $ids)) {
                $ids = $id;
            } else {
                $ids = [];
            }
        }
        $condition['id'] = $ids;
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $wikiList = AdmWiki::admWikiList($condition);
        $gridModel = new pGridDataModel($wikiList['list'], $wikiList['total'], [
            'perPage' => $pageSize
        ]);
        $type = self::PACKAGE_EDIT_TYPE;
        return $content
            ->header('内部品牌清单')
            ->description(' ')
            ->row(
                Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $packageId, $type) {
                        $grid->paginate($gridModel->getPerPage());
                        $grid->filter(function ($filter) {
                            // 去掉默认的id过滤器
                            $filter->disableIdFilter();
                            // 在这里添加字段过滤器
                            $filter->column(1 / 2, function ($filter) {
                                $filter->equal('id', '商品ID')->placeholder('商品ID');

                            });

                            $filter->expand();//默认展开
                        });
                        $grid->disableExport();
                        $grid->disableCreateButton();
                        $grid->disableRowSelector();
                        $grid->column('id', 'id');
                        $grid->column('basic_id', 'WIKI_ID');
                        $grid->column('title', '名称');
                        $grid->column('card_img', '首图')->width(200)->display(function () {
                            $imgPath = $this->cover_img;
                            $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='height:200px' class='img img-thumbnail' />" : "";
                            return $image;
                        });
                        $grid->column('channel_brand', '品牌');
                        $grid->column('channel_shop_name', '店铺名称');
                        $grid->column('brand_uid', '品牌/店铺账号ID');
                        $grid->column('brand_nick', '品牌/店铺账号昵称')->display(function () {
                            return '<span>' . $this->brand_nick . '</span><span class="label label-success">' . ($this->brand_info ? '类型:' . mBrand::BRAND_TYPE[$this->brand_info['brand_type']] : '') . '</span>';
                        });
                        $grid->column('addtime', '创建时间');
                        $grid->column('status_desc', '状态');
                        $grid->column('category_desc', '商城类目');
                        $grid->actions(function (Grid\Displayers\Actions $actions) use ($packageId, $type) {
                            $actions->disableEdit();
                            $actions->disableDelete();
                            $actions->prepend('&nbsp;<a class="fa fa-edit" target="" href="' . url('/admin/wiki/admList/' . $actions->row->id . '/edit?pack_type=' . $type . '&package_id=' . $packageId) . '">编辑</a>');
                        });
                    }
                )
            );
    }

    private function _filter_request(Request $request)
    {
        $params = $request->all();
        unset($params['_pjax']);
        return http_build_query($params);
    }

    public function _index_condition($request)
    {
        $response = [];

        //商品名称条件
        if (isset($request['wiki_type'])) {
            $wiki_value = trim($request['wiki_type']);
            if (strlen($wiki_value)) {
                $response['title[~]'] = $wiki_value;
            }
        }
        //wiki Id条件
        if (isset($request['wiki_id']) && ($request['wiki_id'] > 0)) {
            $response['id'] = $request['wiki_id'];
        }

        if (isset($request['wiki_basic_style']) && !empty($request['wiki_basic_style'])) {
            $basicIds = EsWikiListModel::queryByBasicStyle($request['wiki_basic_style']);
            if($basicIds){
                $response['basic_id'] = $basicIds;
            }
        }
        if (isset($request['basic_id']) && ($request['basic_id'] > 0)) {
            $response['basic_id'] = $request['basic_id'];
        }

        if (isset($request['channel_spu_id']) && ($request['channel_spu_id'] > 0)) {
            $response['channel_spu_id'] = $request['channel_spu_id'];
        }


        if (isset($request['channel_type']) && ($request['channel_type'])) {
            $response['channel_type'] = $request['channel_type'];
        }
        if (isset($request['channel_spu_status']) && $request['channel_spu_status'] != '') {
            $response['channel_spu_status'] = $request['channel_spu_status'];
        }
        //品牌账号条件
        if (isset($request['brand_type'])) {
            $brand_value = trim($request['brand_type']);
            if (strlen($brand_value)) {
                $brand_uid = AdmWiki::admSearchUid($brand_value);
                if ($brand_uid > 0) {
                    $response['OR'] = [
                        'brand_uid' => $brand_uid,
                        'shop_uid' => $brand_uid,
                    ];
                } else {
                    $response['brand_uid'] = -1;
                }
            }
        }
        //品牌账号ID
        if (isset($request['brand_value']) && is_numeric($request['brand_value'])) {
            $response['OR'] = [
                'brand_uid' => $request['brand_value'],
                'shop_uid' => $request['brand_value'],
            ];
        }
        if (isset($request['brand_id']) && is_numeric($request['brand_id'])) {
            $response['brand_id'] = $request['brand_id'];
        }
        if (isset($request['brand_name']) && strlen($request['brand_name']) > 0) {
            $brandIds = mBrand::selectByWhere(['brand_name[~]' => $request['brand_name']], '*');
            $brandIds = $brandIds ? array_column($brandIds, 'id') : [];
            if ($brandIds) {
                $response['brand_id'] = $brandIds;
            }
        }
        if (isset($request['store_id']) && is_numeric($request['store_id'])) {
            $response['store_id'] = $request['store_id'];
        }
        if (isset($request['store_name']) && strlen($request['store_name']) > 0) {
            $storeIds = mStoreBasic::select('id', ['name[~]' => $request['brand_name']]);
            if ($storeIds) {
                $response['store_id'] = $storeIds;
            }
        }

        //创建时间条件
        if (isset($request['date_time']['start']) && strlen($request['date_time']['start'])) {
            $response['addtime[>=]'] = $request['date_time']['start'];
        }
        if (isset($request['date_time']['end']) && strlen($request['date_time']['end'])) {
            $response['addtime[<=]'] = $request['date_time']['end'];
        }

        //店铺名称条件
        $shop_name = isset($request['shop_name']) ? trim($request['shop_name']) : '';
        if (strlen($shop_name)) {
            $response['channel_shop_name'] = $shop_name;
        }

        //商城类目条件
//        if (isset($request['category_id']) && ($request['category_id'] != 0)) {
//            $category_id = $request['category_id'];
//            if ($category_id == -1) {
//                $response['last_category_id'] = 0;
//            } else {
//                $last_category_id = [];
//                if (isset($request['second_category_id']) && ($request['second_category_id'] > 0)) {
//                    $category_id = $request['second_category_id'];
//                }
//                if ($category_id > 0) {
//                    $last_category_id = array_merge([$category_id], $last_category_id, AdmWiki::admGetChildCategoryIds($category_id));
//                    $response['last_category_id'] = $last_category_id;
//                }
//            }
//        }
        if (isset($request['category_id']) && $request['category_id']) {
            $response['category_id'] = $request['category_id'];
        }
        if (isset($request['second_category_id']) && $request['second_category_id']) {
            $response['second_category_id'] = $request['second_category_id'];
        }
        if (isset($request['third_category_id']) && $request['third_category_id']) {
            $response['third_category_id'] = $request['third_category_id'];
        }
        if (isset($request['four_category_id']) && $request['four_category_id']) {
            $response['four_category_id'] = $request['four_category_id'];
        }


        //wiki状态
        if (isset($request['status']) && ($request['status'] !== '')) {
            $response['status'] = $request['status'];
        }

        //未审核原因
        if (isset($request['reason']) && $request['reason'] > 0) {
            $ids = AdmWiki::admSearchContentByReason($request['reason']);
            if (!empty($ids)) {
                $response['id'] = $ids;
            } else {
                $response['id'] = 0;
            }
        }
        return $response;
    }

    public function wikiReload(Request $request, $id = 0)
    {
        try {
            $v = mWiki::getByWhere(['id' => $id]);
            if (!$v) {
                throw new \Exception('wiki信息不存在');
            }

            $wikiInfo = $v ? AdmWiki::admReloadWiki($v) : [];

            $success = new MessageBag([
                'title' => 'wiki ID: ' . $id . ' 重新抓取成功'
            ]);
        } catch (\Exception $e) {
            $success = new MessageBag([
                'title' => '修改失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ]);
        }
        ob_end_clean();
        return response()->json($success);
    }

    public function offLineWiki(Request $request, $id = 0)
    {
        try {
            $v = mWiki::getByWhere(['id' => $id]);
            if (!$v) {
                throw new \Exception('wiki信息不存在');
            }
            AdmWiki::admOfflineWiki($id, Admin::user()->id);
            //选品中心下架
            SelectionLib::updateItemByWikiId($id, ['select_status' => mWiki::STATUS_DEL]);
            //选品中心下架
            $success = [
                'title' => 'wiki ID: ' . $id . ' 下架成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '修改失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function setOfficial(Request $request, $id = 0)
    {
        try {
            $v = mWiki::getByWhere(['id' => $id]);
            if (!$v) {
                throw new \Exception('wiki信息不存在');
            }
            mWiki::updateData(['is_official' => 1], ['id' => $id]);
            $success = [
                'title' => 'wiki ID: ' . $id . ' 设置为官方商品成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '修改失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function wikiSave(Request $request, $id = 0)
    {
        try {
            $type = $request->post('pack_type', '');
            $package_id = $request->post('package_id', '');
            $requestUrl = $request->post('request_url', '');
            if (!$id) {
                throw new \Exception('参数错误');
            }

            $info = AdmWiki::getInfoById($id);
            if (!$info) {
                throw new \Exception('修改的记录不存在');
            }
            $title = trim($request->post('title'));
            if (mb_strlen($title) < 0) {
                throw new \Exception('商品名称不能为空');
            }
            //商品首图,和商品图列表
            $imgs = trim($request->post('imgs', ''));
            $detail_imgs = trim($request->post('detail_imgs', ''));

            $temp_img = explode(',', $imgs);
            $temp_detail_img = explode(',', $detail_imgs);

            $imgs = empty($temp_img) ? "" : json_encode($temp_img);

            $detail_imgs = empty($temp_detail_img) ? "" : json_encode($temp_detail_img);
            $cover_img = empty($temp_img) ? "" : array_shift($temp_img);

            //未审核原因
            $reason = intval($request->post('reason', 0));

            //末级类目id赋值
            $category_id = 0;
            $second_category_id = 0;
            $third_category_id = 0;
            $four_category_id = 0;
            $last_category_id = 0;
            $fullCategory = $request->post('full_category', '');
            if ($fullCategory) {
                $fullCategory = explode('-', $fullCategory);
                $category_id = $fullCategory[0] ?? 0;
                $second_category_id = $fullCategory[1] ?? 0;
                $third_category_id = $fullCategory[2] ?? 0;
                $four_category_id = $fullCategory[3] ?? 0;
            }
            if ($reason == 0 && $info['brand_id'] == 0) {
                if ($category_id <= 0) {
                    throw new \Exception('商城一级类目必须选择');
                }

                if ($second_category_id <= 0) {
                    throw new \Exception('商城二级类目必须选择');
                }
                $last_category_id = $second_category_id;

                if ($third_category_id > 0) {
                    $last_category_id = $third_category_id;
                }
                if ($four_category_id > 0) {
                    $last_category_id = $four_category_id;
                }
                if ($last_category_id <= 0) {
                    throw new \Exception('商城类目必须选择');
                }
            }

            $min_price = floatval($request->post('min_price', 0.0));
            $max_price = floatval($request->post('max_price', 0.0));

            //品牌赋值
            $brand_id = intval($request->post('brand_id', 0));
            $tags = $request->post('tags', []);
            $tags = implode(",", array_filter($tags));
            $channel_shop_id = trim($request->post('channel_shop_id', ''));
            $channel_seller_id = trim($request->post('channel_seller_id', ''));
            //商品打标签数据
            $wiki_basic_style = $request->post('wiki_basic_style', []);
            if ($wiki_basic_style) {
                $wiki_basic_style = implode(',', array_filter($wiki_basic_style));
            }
            //商品短名
            $simple_title = $request->post('simple_title', '');

            //商品场景图
            $scene_img = '';
            $is_up_scene_img = $request->post('is_up_scene_img', self::UP_SCENE_IMG_NO);
            if (self::UP_SCENE_IMG_YES == $is_up_scene_img) {
                $scene_img = $cover_img;
            }
            $saveData = compact('title', 'last_category_id', 'brand_id', 'cover_img', 'tags', 'category_id',
                'second_category_id', 'third_category_id', 'four_category_id', 'channel_shop_id', 'channel_seller_id', 'min_price',
                'max_price', 'simple_title', 'scene_img');
            if ($info['channel_type'] == mWiki::CHANNEL_TYPE_AMAZON) {
                unset($saveData['cover_img']);
            }
            // 如果场景图是空的 则unset掉
            if (empty($scene_img)) {
                unset($saveData['scene_img']);
            }
            // 如果场景图选择了清空 则把场景图改为空
            if (self::UP_SCENE_IMG_DEL == $is_up_scene_img) {
                $saveData['scene_img'] = '';
            }
            $basicData = [];
            if ($info['brand_id']) {//已经存在品牌，不能修改分类及品牌id
                unset($saveData['brand_id']);
                unset($saveData['category_id']);
                unset($saveData['second_category_id']);
                unset($saveData['third_category_id']);
                unset($saveData['four_category_id']);
                unset($saveData['last_category_id']);
                $categoryCheck = $info['last_category_id'] > 0;
            } else {
                $basicData = [
                    'brand_id' => $saveData['brand_id'],
                    'category_id' => $saveData['category_id'],
                    'second_category_id' => $saveData['second_category_id'],
                    'third_category_id' => $saveData['third_category_id'],
                    'four_category_id' => $saveData['four_category_id'],
                    'last_category_id' => $saveData['last_category_id'],
                ];
                if (($info['brand_id'] == 0 || ($info['brand_id'] > 0 && $info['is_official'] != mWiki::IS_OFFICIAL_Y)) && $info['store_id'] == 0) {
                    $basicData = array_merge($basicData, ['style' => $wiki_basic_style]);
                }
                $categoryCheck = $saveData['last_category_id'] > 0;
            }
            if ($categoryCheck) {
                $saveData['status'] = mWiki::STATUS_CHECKED;
            } else {
                $saveData['status'] = mWiki::STATUS_WAIT_CHECK;
            }
            if (!$saveData['title']) {
                $saveData['status'] = mWiki::STATUS_NORMAL;
            }
            $rs = AdmWiki::admSaveWiki($saveData, ['id' => $id]);
            if ($basicData && $info['basic_id']) {
                mWikiBasic::updateData($basicData, ['id' => $info['basic_id']]);
            }
            if (!$rs) {
                throw new \Exception('更新信息失败,刷新后再试');
            }
            $operator = Admin::user()->id;
            $content_text = trim($request->post('content_text', ''));
            $content_style = trim($request->post('content_style', ''));
            $content = $content_style . $content_text;
            $content_change = $request->post('content_change', 0);
            $saveContent = $content_change > 0 ? compact('imgs', 'reason', 'operator', 'content',
                'detail_imgs') : compact('imgs', 'reason', 'operator', 'detail_imgs');
            if ($info['channel_type'] == mWiki::CHANNEL_TYPE_AMAZON) {
                unset($saveContent['imgs']);
            }
            if (!empty($type) && !empty($package_id)) {
                $where_pack['package_id'] = $package_id;
                $where_pack['claimant'] = Admin::user()->id;
                $where_pack['wiki_id'] = $id;
                $pack_data = [
                    'edittime' => date("Y-m-d H:i:s"),
                    'has_check' => self::PACKAGE_RELATED_CHECKD,
                ];
                PackageRelatedInfo::update($pack_data, $where_pack);
            }

            $rs = AdmWiki::admSaveWikiContent($saveContent, $id);
            // 选品中心
            $selectedData = [];
            if ($saveData['last_category_id'] > 0) {
                $selectedData = [
                    'category_id' => $saveData['category_id'],
                    'second_category_id' => $saveData['second_category_id'],
                    'third_category_id' => $saveData['third_category_id'],
                    'four_category_id' => $saveData['four_category_id'],
                    'last_category_id' => $saveData['last_category_id'],
                ];
            }
            if ($saveData['status']) {
                $selectedData['select_status'] = $saveData['status'];
            }
            if ($selectedData && is_array($selectedData)) {
                SelectionLib::updateItemByWikiId($id, $selectedData);
            }
            //选品中心
            if (!$rs) {
                throw new \Exception('更新内容信息失败,刷新后再试');
            }
            $success = new MessageBag([
                'title' => '修改成功'
            ]);
            if (!empty($requestUrl)) {
                return redirect($requestUrl);
            }
            if (!empty($type) && !empty($package_id)) {
                return redirect('/admin/wiki/pack_list?package_id=' . (int)$package_id . $request->getQueryString())->with(compact('success'));
            }
            return redirect('/admin/wiki/admList?' . $request->getQueryString())->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '修改失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function wikiEdit(Request $request, Content $content, $id = 0)
    {
        $params = $request->all();
        $type = isset($params['pack_type']) ? $params['pack_type'] : '';
        $package_id = isset($params['package_id']) ? $params['package_id'] : '';

        //编辑wiki
        $baseInfo = AdmWiki::getInfoById($id);
        $baseInfo['imgs'] = empty($baseInfo['imgs']) ? '' : implode(',', json_decode($baseInfo['imgs'], true));
        $baseInfo['detail_imgs'] = empty($baseInfo['detail_imgs']) ? '' : implode(',',
            json_decode($baseInfo['detail_imgs'], true));

        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => 'wiki不存在'
            ]);
            return redirect('/admin/wiki/admList')->with(compact('error'));
        }
        if (!empty($type) && !empty($package_id)) {
            $baseInfo['pack_type'] = $type;
            $baseInfo['package_id'] = $package_id;
        }
        $matchCategory = '';
        if (empty($baseInfo['last_category_id'])) {
            //todo 检索商品名称中是否包含好好住分类名称
            $options = \Doraemon\service\Category::admAllCate4Select();
            $title = $baseInfo['title'] ?? '';
            $match = false;
            foreach ($options as $key => $v) {
                $v = explode("-", $v);
                foreach ($v as $i => $keyWord) {
                    if (strstr($title, $keyWord)) {
                        if ($i > 1) {
                            $matchCategory = $key;
                            $match = true;
                            break;
                        }
                    }
                }
                if ($match) {
                    break;
                }
            }
        }
        if ($matchCategory && ($baseInfo['brand_id'] == 0)) {
            $full_category = explode("_", $matchCategory);
            $baseInfo['category_id'] = $full_category[0] ?? 0;
            $baseInfo['second_category_id'] = $full_category[1] ?? 0;
            $baseInfo['third_category_id'] = $full_category[2] ?? 0;
            $baseInfo['four_category_id'] = $full_category[3] ?? 0;
            admin_warning('提示', '自动匹配了分类，请核对分类信息后再保存');
        }
        $baseInfo['full_category'] = implode('-', array_filter([$baseInfo['category_id'], $baseInfo['second_category_id'], $baseInfo['third_category_id'], $baseInfo['four_category_id']]));
        if (($baseInfo['brand_id'] == 0 || ($baseInfo['brand_id'] > 0 && $baseInfo['is_official'] != mWiki::IS_OFFICIAL_Y)) && $baseInfo['store_id'] == 0 && $baseInfo['wiki_basic_style_match'] && !empty($baseInfo['wiki_basic_style'])) {
            admin_info('提示', '自动匹配了商品风格标签，请核对标签信息后再保存');
        }
        $styleList = AdmWikiTag::getStyleList();
        Admin::script($this->imgSubmitScript());
        $query = $this->_filter_request($request);
        $requestUlr = url()->previous();
        $baseInfo['request_url'] = $requestUlr;
        $allBrands = AdmWiki::admGetBrandList();
        $allCategoryOption = $this->getAllCategoryOption();
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        $baseForm->html('<div class="btn-group pull-right">
                <button type="submit" class="btn btn-info pull-right">提交</button>
            </div>');
        $baseForm->text('title', '商品名称');
        if (($baseInfo['brand_id'] == 0 || ($baseInfo['brand_id'] > 0 && $baseInfo['is_official'] != mWiki::IS_OFFICIAL_Y)) && $baseInfo['store_id'] == 0) {
            $baseForm->text('simple_title', '商品短名');
        } else {
            $baseForm->text('simple_title', '商品短名')->disable();
        }
        if ($baseInfo['brand_id']) {
            $baseForm->select('full_category', '商品分类')->options($allCategoryOption)->disable();
        } else {
            $baseForm->select('full_category', '商品分类')->options($allCategoryOption);
        }
        $baseForm->tags('tags', '商品标签（第三方）')->disable()->placeholder('暂无');
        if (($baseInfo['brand_id'] == 0 || ($baseInfo['brand_id'] > 0 && $baseInfo['is_official'] != mWiki::IS_OFFICIAL_Y)) && $baseInfo['store_id'] == 0) {
            $baseForm->tags('wiki_basic_style', '商品风格标签')->options($styleList);
        } else {
            $baseForm->tags('wiki_basic_style', '商品风格标签')->options($styleList)->disable();
        }
        $baseForm->text('channel_brand', '品牌名称（第三方）')->prepend($this->clipboardHtml('channel_brand'))->readonly();

        if ($baseInfo['brand_id']) {
            if ($baseInfo['channel'] == mWiki::CHANNEL_MAP[mWiki::CHANNEL_NOTHING]) {
                $baseForm->select('brand_id', '品牌')->options($allBrands)->disable();
            } else {
                $baseForm->select('brand_id', '品牌')->options($allBrands);
            }
        } else {
            $baseForm->select('brand_id', '品牌')->options($allBrands);
        }
        $baseForm->select('reason', '未审核原因')->options(AdmWiki::REJECT_MSG_MAP);

        $baseForm->divider('图片相关');
        $baseForm->imgUpload('imgs', '商品主图', true, ['isUpload' => false, 'isGetUrl' => false])->help('首图尽量选择场景图，场景图要求：1. 无促销价格信息和影响整体氛围的文字信息 2. 商品在视觉中心点，且展示完整');
        $baseForm->radio('is_up_scene_img', '更新场景图')->options([self::UP_SCENE_IMG_YES => '更新', self::UP_SCENE_IMG_NO => '不更新', self::UP_SCENE_IMG_DEL => '清空场景图'])->default(self::UP_SCENE_IMG_NO)->help('更新:将上方第一张商品图更新为场景图；不更新:下方场景图不变；');
        $baseForm->imgUpload('scene_img', '商品场景图', false, ['isUpload' => false, 'isGetUrl' => false]);
        $baseForm->imgUpload('white_image', '商品白底图', false, ['isUpload' => false, 'isGetUrl' => false]);

        $baseForm->divider('基础信息');
        $baseForm->text('url', '商品链接')->prepend($this->clipboardHtml('url'))->readonly();
        $baseForm->text('min_price', '商品最低价格')->prepend($this->clipboardHtml('min_price'));
        $baseForm->text('max_price', '商品最高价格')->prepend($this->clipboardHtml('max_price'));
        $baseForm->text('channel', '数据来源')->prepend($this->clipboardHtml('channel'))->readonly();
        $baseForm->text('channel_shop_name', '第三方店铺名称')->prepend($this->clipboardHtml('channel_shop_name'))->readonly();
        $baseForm->text('channel_shop_id', '第三方店铺ID');
        $baseForm->text('channel_seller_id', '第三方卖家ID');
        $relateNoteId = explode(',', $baseInfo['relate_note_id']);
        $relateNoteId = array_filter($relateNoteId) ? array_shift($relateNoteId) : '';
        if ($relateNoteId) {
            $baseForm->text('relate_note_id',
                '关联图片ID')->prepend($this->clipboardHtml('relate_note_id'))->readonly()->help("<a target='_blank' href='https://frieza.haohaozhu.me/admin/photo/photocheck/index?&photo_id=" . $relateNoteId . "'>" . $relateNoteId . "</a>");
        } else {
            $baseForm->text('relate_note_id', '关联图片ID')->prepend($this->clipboardHtml('relate_note_id'))->readonly();
        }
        $baseForm->text('relate_blank_id', '关联文章ID')->prepend($this->clipboardHtml('relate_blank_id'))->readonly();
        if (!empty($type) && !empty($package_id)) {
            $baseForm->hidden('pack_type', $type);
            $baseForm->hidden('package_id', $package_id);
        }

        if ($baseInfo['channel'] == mWiki::CHANNEL_MAP[mWiki::CHANNEL_NOTHING]) {
            $baseForm->imgUpload('detail_imgs', '商品详情图', true, [
                'isUpload' => false,
                'isGetUrl' => true,
                'imgType' => ImgUrl::APPTYPE_BIZ,
                'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG
            ]);
        } else {
            $baseForm->ckEditor('content_text', '商品详情')->attribute(['change_id' => 'content_change']);
            $baseForm->hidden('content_change', '商品详情')->attribute(['id' => 'content_change']);
        }
        $baseForm->hidden('request_url', 'request_url');
        $baseForm->action('/admin/wiki/admList/' . $id . '/save?' . $query);
        return $content
            ->header('审核wiki商品')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'wiki商品', 'url' => '/wiki/admList'],
                ['text' => '审核wiki商品']
            )
            ->row($baseForm);
    }

    public function addWiki(Content $content)
    {
        $form = new Form();
        $form->textarea('url', '淘宝或京东商品链接')->help('多个链接用,分隔');
        $form->action('/admin/wiki/admList/insert');
        return $content
            ->header('添加wiki')
            ->breadcrumb(
                [
                    'text' => 'wiki商品列表',
                    'url' => '/wiki/admList'
                ],
                ['text' => '添加']
            )
            ->row($form);
    }

    public function insertWiki(Request $request)
    {
        try {
            $url = str_replace("，", ',', trim($request->post('url')));
            $urls = strlen($url) ? explode(",", $url) : [];
            if (empty($urls)) {
                throw new \Exception('链接为空');
            }
            $urls = array_filter($urls);

            foreach ($urls as $content) {
                if ($content = trim($content)) {
                    Wiki::addGetWikiSpuTask($content);
                }
            }

            $success = new MessageBag([
                'title' => '添加抓取任务成功,稍后刷新页面进行查看'
            ]);
            return redirect('/admin/wiki/admList?' . $request->getQueryString())->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '添加抓取任务失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function editLike(Request $request, \App\Admin\Extensions\WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info = mWiki::getByWhere(['id' => $id]);
        $form = new Form($info);
        $form->hidden('id');
        $form->hidden('type');
        $form->text('defined_increment', '基础分值')->required();
        $form->disableReset();
        $form->action('/admin/wiki/admList/' . $id . '/postEditLike');
        return $content
            ->body($form);
    }

    public function postEditLike(Request $request, $id)
    {
        $num = $request->input('defined_increment', 0);
        $res = mWiki::updateData(['defined_increment' => $num], ['id' => $id]);
        if (!$res) {
            return response()->json(['stauts' => false, 'message' => '操作失败']);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        return redirect('/admin/wiki/admList/' . $id . '/editLike?code=1')->with(compact('success'));
    }

    private function clipboardHtml($id)
    {
        return "<span style='cursor: pointer;'><i class='fa fa-clipboard copyBtn'  data-clipboard-target='#{$id}'></i></span>";
    }

    private function reloadScript($query)
    {
        return <<<SCRIPT
        $('.reload-data').unbind('click').click(function(){
            let url = 'admList/' +  $(this).data('id')  + '/reload'
            let params = {}
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success('重新抓取任务已经添加,稍后刷新页面进行查看');
            });
        });
        
        var singleDownLoad = true;
        $('.download').unbind('click').click(function(){
            if (singleDownLoad == false) {
                return;
            }
            singleDownLoad = false;
            sign = 1
            if (sign > 0) {
                $.ajax({
                    url:'/admin/wiki/admList/export?$query',
                    type:"GET",
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    complete : function(){
                        singleDownLoad = true;
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
            }
         });
SCRIPT;
    }

    private function editLikeScript()
    {
        return <<<SCRIPT
        $('.like-data').unbind('click').click(function(){
            var id=$(this).data('id');
            layer.open({
                type: 2,
                title: '编辑',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['300px', '300px'],
                content: '/admin/wiki/admList/'+id+'/editLike',
            });
        });
SCRIPT;
    }

    private function offlineScript()
    {
        return <<<SCRIPT
        $('.grid-table').on('click', '.grid-column-copyable', (function (e) {
            var content = $(this).data('content');
            var temp = $('<input>');
            $("body").append(temp);
            temp.val(content).select();
            document.execCommand("copy");
            temp.remove();
            $(this).tooltip('show');
        }));
        $('.offline-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要下架该wiki:'+id+'吗？')){
                let url = '/admin/wiki/admList/' +  $(this).data('id')  + '/offline'
                let params = {}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            }
        });
        $('.set-official').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定把该wiki:'+id+'设置为官方商品吗？')){
                let url = '/admin/wiki/admList/' +  $(this).data('id')  + '/setOfficial'
                let params = {}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            }
        });
SCRIPT;
    }


    public function export(Request $request)
    {
        $status = 1;
        $message = '导出内容将发送至邮箱,请稍后查看';
        try {
            $adminEmail = Admin::user()->email;
            if (empty($adminEmail)) {
                throw new \Exception('导出内容将发送至邮箱(' . $adminEmail . '),请先设置邮箱');
            }
            $requestParams = $request->all();
            $condition = $this->_index_condition($requestParams);
            //发送邮件
            ExportData::addTask([AdmWiki::class, 'admExportWikiList'], [$adminEmail, $condition]);
        } catch (\Exception $e) {
            $message = $e->getMessage();
            $status = 0;
        }
        return response()->json(compact('status', 'message'));
    }

    private function imgSubmitScript()
    {
        return <<<EOD
$.getScript('/vendor/js/clipboard/dist/clipboard.min.js', function(){
    //避免pjax重复加载js导致事件重复绑定
        if (typeof (pjax_isLoad) != "undefined") {
            return;
        }
        pjax_isLoad = true;
        let copyBtn = new ClipboardJS(".copyBtn");
        copyBtn.on("success",function(e){
            // 复制成功
             console.log( e)
             if (e.text.length > 0) {
                toastr.success('复制成功');
             }
             e.clearSelection();
        });
        copyBtn.on("error",function(e){
            //复制失败
            console.log( e.action )
        });
});
EOD;
    }

    private function getAllCategoryOption()
    {
        $allCategory = Category::getAllCategorys();
        $optionArr = [];
        foreach ($allCategory as $firstId => $firstInfo) {
            $firstCateName = $firstInfo['cate_name'];
            $optionArr[$firstId] = $firstCateName;
            if (isset($firstInfo['children']) && $firstInfo['children']) {
                foreach ($firstInfo['children'] as $secondId => $secondInfo) {
                    $secondCateName = $secondInfo['cate_name'];
                    $optionArr[$firstId . '-' . $secondId] = $firstCateName . '>>' . $secondCateName;
                    if (isset($secondInfo['children']) && $secondInfo['children']) {
                        foreach ($secondInfo['children'] as $thirdId => $thirdInfo) {
                            $thirdCateName = $thirdInfo['cate_name'];
                            $optionArr[$firstId . '-' . $secondId . '-' . $thirdId] = $firstCateName . '>>' . $secondCateName . '>>' . $thirdCateName;
                            if (isset($thirdInfo['children']) && $thirdInfo['children']) {
                                foreach ($thirdInfo['children'] as $fourId => $fourInfo) {
                                    $fourCateName = $fourInfo['cate_name'];
                                    $optionArr[$firstId . '-' . $secondId . '-' . $thirdId . '-' . $fourId] = $firstCateName . '>>' . $secondCateName . '>>' . $thirdCateName . '>>' . $fourCateName;
                                }
                            }
                        }
                    }
                }
            }
        }
        return $optionArr;
    }
}
